package pers.fulsun.demo.springcloud.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * mybatisplus自定义填充公共字段 ,即没有传的字段自动填充
 *
 * @author fulsun
 * @create: 2021-08-19 14:17
 */
//@Component
public class MPMetaObjectHandler implements MetaObjectHandler {
    /**
     * 获取逻辑删除的未删除值作为默认初始值
     */
    @Value("${mybatis-plus.global-config.db-config.logic-not-delete-value}")
    private Integer isDeleteDefaultValue;

    /**
     * 插入填充
     *
     * @param metaObject 目标对象
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        Object createBy = metaObject.getValue("createBy");
        Object createDate = metaObject.getValue("createDate");
        Object isDelete = metaObject.getValue("isDelete");
        //判断是否存在该字段
        if (null == createBy) {
            this.setFieldValByName("createBy", "admin", metaObject);
        }
        if (null == createDate) {
            this.setFieldValByName("createDate", LocalDateTime.now(), metaObject);
        }
        //填充isDelete属性
        if (null == isDelete) {
            this.setFieldValByName("isDelete", isDeleteDefaultValue, metaObject);
        }
        this.updateFill(metaObject);
    }

    /**
     * 更新填充
     *
     * @param metaObject 目标对象
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        Object updateBy = metaObject.getValue("updateBy");
        Object updateDate = metaObject.getValue("updateDate");
        //设置当前登录用户
        if (null == updateBy) {
            this.setFieldValByName("updateBy", "admin", metaObject);
        }
        if (null == updateDate) {
            this.setFieldValByName("updateDate", LocalDateTime.now(), metaObject);
        }
    }

}
